<template>
  <div class="finance-report">
    <!-- 财务汇总卡片 -->
    <el-row :gutter="20" class="mb-4">
      <el-col :span="6">
        <el-card shadow="hover" class="summary-card income">
          <div class="card-content">
            <div class="card-title">总收入</div>
            <div class="card-value">
              ¥
              {{
                totalIncome.toLocaleString("zh-CN", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })
              }}
            </div>
            <div class="card-change" :class="incomeChangeClass" v-if="props.label != 'custom'">
              {{ incomeChangeText }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="summary-card cost">
          <div class="card-content">
            <div class="card-title">总成本</div>
            <div class="card-value">
              ¥
              {{
                totalCost.toLocaleString("zh-CN", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })
              }}
            </div>
            <div class="card-change" :class="costChangeClass" v-if="props.label != 'custom'">
              {{ costChangeText }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="summary-card profit">
          <div class="card-content">
            <div class="card-title">总利润</div>
            <div class="card-value">
              ¥
              {{
                totalProfit.toLocaleString("zh-CN", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })
              }}
            </div>
            <div class="card-change" :class="profitChangeClass"  v-if="props.label != 'custom'">
              {{ profitChangeText }}
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="summary-card rate">
          <div class="card-content">
            <div class="card-title">利润率</div>
            <div class="card-value">
              {{
                profitRate.toLocaleString("zh-CN", {
                  minimumFractionDigits: 2,
                  maximumFractionDigits: 2,
                })
              }}%
            </div>
            <div class="card-change" :class="profitRateChangeClass"  v-if="props.label != 'custom'">
              {{ profitRateChangeText }}
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="mt-15">
      <el-col :span="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>财务趋势图</span>
              <el-radio-group v-model="chartType" @change="updateChart">
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="line">折线图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div
            id="trendChart"
            ref="trendChartRef"
            class="chart-container"
          ></div>
        </el-card>
      </el-col>
      <el-col :span="12" class="mt-15">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>收入成本占比</span>
            </div>
          </template>
          <div id="pieChart" ref="pieChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12" class="mt-15">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>利润率变化</span>
            </div>
          </template>
          <div id="rateChart" ref="rateChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  watch,
  nextTick,
  getCurrentInstance,
} from "vue";
import * as echarts from "echarts";
import { debounce } from "lodash-es";

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();

const { $http, $ekMessage } = globalProperties;

const props = defineProps({
  // 显示/隐藏
  label: {
    type: String,
    default: "",
  },
  // 时间范围
  dateRange: {
    type: Array,
    default: () => [],
  },
});

// 图表类型
const chartType = ref("bar");

// 图表引用
const trendChartRef = ref(null);
const pieChartRef = ref(null);
const rateChartRef = ref(null);

// 图表实例
let trendChart = null;
let pieChart = null;
let rateChart = null;

// 汇总数据
const totalIncome = ref(0);
const totalCost = ref(0);
const totalProfit = ref(0);
const profitRate = ref(0);

// 同比数据
const lastTotalIncome = ref(0);
const lastTotalCost = ref(0);
const lastTotalProfit = ref(0);
const lastProfitRate = ref(0);

// 同比变化
const incomeChangeClass = ref("");
const incomeChangeText = ref("");
const costChangeClass = ref("");
const costChangeText = ref("");
const profitChangeClass = ref("");
const profitChangeText = ref("");
const profitRateChangeClass = ref("");
const profitRateChangeText = ref("");

// 图表数据
const chartData = ref({
  categories: [],
  incomeData: [],
  costData: [],
  profitData: [],
  rateData: [],
});
const chartLastData = ref({
  categories: [],
  incomeData: [],
  costData: [],
  profitData: [],
  rateData: [],
});

// 模拟数据
const mockChartData = {
  categories: ["1月", "2月", "3月", "4月", "5月", "6月"],
  incomeData: [1200000, 1320000, 1010000, 1340000, 900000, 1500000],
  costData: [800000, 900000, 700000, 950000, 650000, 1100000],
  profitData: [400000, 420000, 310000, 390000, 250000, 400000],
  rateData: [33.3, 31.8, 30.7, 29.1, 27.8, 26.7],
};

// 初始化图表
const initCharts = () => {
  // 销毁现有图表
  if (trendChart) trendChart.dispose();
  if (pieChart) pieChart.dispose();
  if (rateChart) rateChart.dispose();

  // 初始化趋势图
  trendChart = echarts.init(trendChartRef.value);
  // 初始化饼图
  pieChart = echarts.init(pieChartRef.value);
  // 初始化利润率图
  rateChart = echarts.init(rateChartRef.value);

  // 更新图表
  updateChart();
};

// 更新图表数据
const updateChart = () => {
  // 更新趋势图
  updateTrendChart();
  // 更新饼图
  updatePieChart();
  // 更新利润率图
  updateRateChart();
};

// 更新趋势图
const updateTrendChart = () => {
  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999",
        },
      },
    },
    legend: {
      data: ["收入", "成本", "利润"],
    },
    xAxis: [
      {
        type: "category",
        data: chartData.value.categories,
        axisPointer: {
          type: "shadow",
        },
      },
    ],
    yAxis: [
      {
        type: "value",
        name: "金额(元)",
        min: 0,
        max:
          Math.max(...chartData.value.incomeData, ...chartData.value.costData) *
          1.2,
        axisLabel: {
          formatter: "{value}",
        },
      },
    ],
    series: [
      {
        name: "收入",
        type: chartType.value,
        data: chartData.value.incomeData,
        itemStyle: {
          color: "#5470c6",
        },
      },
      {
        name: "成本",
        type: chartType.value,
        data: chartData.value.costData,
        itemStyle: {
          color: "#91cc75",
        },
      },
      {
        name: "利润",
        type: chartType.value,
        data: chartData.value.profitData,
        itemStyle: {
          color: "#fac858",
        },
      },
    ],
  };
  trendChart.setOption(option);
};

// 更新饼图
const updatePieChart = () => {
  const option = {
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b}: {c} ({d}%)",
    },
    legend: {
      orient: "vertical",
      left: "left",
      data: ["收入", "成本"],
    },
    series: [
      {
        name: "财务占比",
        type: "pie",
        radius: "50%",
        data: [
          {
            value: totalIncome.value,
            name: "收入",
            itemStyle: { color: "#5470c6" },
          },
          {
            value: totalCost.value,
            name: "成本",
            itemStyle: { color: "#91cc75" },
          },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)",
          },
        },
      },
    ],
  };
  pieChart.setOption(option);
};

// 更新利润率图
const updateRateChart = () => {
  const option = {
    tooltip: {
      trigger: "axis",
      formatter: "{b}: {c}%",
    },
    xAxis: {
      type: "category",
      data: chartData.value.categories,
    },
    yAxis: {
      type: "value",
      name: "利润率(%)",
      axisLabel: {
        formatter: "{value}%",
      },
    },
    series: [
      {
        data: chartData.value.rateData,
        type: "line",
        smooth: true,
        itemStyle: {
          color: "#ee6666",
        },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: "rgba(238, 102, 102, 0.3)",
              },
              {
                offset: 1,
                color: "rgba(238, 102, 102, 0.1)",
              },
            ],
          },
        },
      },
    ],
  };
  rateChart.setOption(option);
};

// 处理窗口大小变化
const handleResize = () => {
  if (trendChart) trendChart.resize();
  if (pieChart) pieChart.resize();
  if (rateChart) rateChart.resize();
};

// 获取数据
const loading = ref(false);
const fetchData = async () => {
  try {
    loading.value = true;
    console.log(props.dateRange, props.label, "请求参数");
    // 模拟API调用
    const res = await $http.get("/business/statistics/financeCount", {
      params: {
        label: props.label,
        start: props.dateRange?.[0] ? props.dateRange[0] : "",
        end: props.dateRange?.[1] ? props.dateRange[1] : "",
      },
    });
    if (res.status === "success") {
      // 使用模拟数据
      let resData = res.data.list;
      let lastResData = res.data.lastList;
      // 设置图表数据

      chartData.value = {
        incomeData: resData.map((item) => item.stat_income),
        costData: resData.map((item) => item.stat_cost),
        profitData: resData.map((item) => item.stat_profit),
        rateData: resData.map((item) => item.stat_profit_rate),
        categories: resData.map((item) => item.stat_date),
      };

      chartLastData.value = {
        incomeData: lastResData.map((item) => item.stat_income),
        costData: lastResData.map((item) => item.stat_cost),
        profitData: lastResData.map((item) => item.stat_profit),
        rateData: lastResData.map((item) => item.stat_profit_rate),
        categories: lastResData.map((item) => item.stat_date),
      };

      // 计算汇总数据
      totalIncome.value = chartData.value.incomeData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );
      lastTotalIncome.value = chartLastData.value.incomeData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );

      totalCost.value = chartData.value.costData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );
      lastTotalCost.value = chartLastData.value.costData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );
      totalProfit.value = chartData.value.profitData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );
      lastTotalProfit.value = chartLastData.value.profitData.reduce(
        (a, b) => Number(a) + Number(b),
        0
      );
      profitRate.value =
        totalIncome.value > 0
          ? (totalProfit.value / totalIncome.value) * 100
          : 0;
      lastProfitRate.value =
        lastTotalIncome.value > 0
          ? (lastTotalProfit.value / lastTotalIncome.value) * 100
          : 0;

      // 设置同比变化（模拟数据）
      incomeChangeClass.value =
        totalIncome.value > lastTotalIncome.value ? "up" : "down";
      incomeChangeText.value =
        totalIncome.value > lastTotalIncome.value
          ? `${calculateGrowth(
              Number(totalIncome.value),
              Number(lastTotalIncome.value)
            ).toFixed(2)}% 同比增长`
          : `${calculateGrowth(
              Number(lastTotalIncome.value),
              Number(totalIncome.value)
            ).toFixed(2)}% 同比减少 `;

      costChangeClass.value =
        totalCost.value > lastTotalCost.value ? "up" : "down";
      costChangeText.value =
        totalCost.value > lastTotalCost.value
          ? `${calculateGrowth(
              Number(totalCost.value),
              Number(lastTotalCost.value)
            ).toFixed(2)}% 同比增长`
          : `${calculateGrowth(
              Number(lastTotalCost.value),
              Number(totalCost.value)
            ).toFixed(2)}% 同比减少 `;

      profitChangeClass.value =
        totalProfit.value > lastTotalProfit.value ? "up" : "down";
      profitChangeText.value =
        totalProfit.value > lastTotalProfit.value
          ? `${calculateGrowth(
              Number(totalProfit.value),
              Number(lastTotalProfit.value)
            ).toFixed(2)}% 同比增长`
          : `${calculateGrowth(
              Number(lastTotalProfit.value),
              Number(totalProfit.value)
            ).toFixed(2)}% 同比减少 `;

      profitRateChangeClass.value =
        profitRate.value > lastProfitRate.value ? "up" : "down";
      profitRateChangeText.value =
        profitRate.value > lastProfitRate.value
          ? `${calculateGrowth(             
              Number(profitRate.value),
              Number(lastProfitRate.value)
            ).toFixed(2)}% 同比增长`
          : `${calculateGrowth(
              Number(lastProfitRate.value),
              Number(profitRate.value)
            ).toFixed(2)}% 同比减少 `;

      profitRateChangeClass.value =
        profitRate.value > lastProfitRate.value ? "up" : "down";
      profitRateChangeText.value =
        profitRate.value > lastProfitRate.value
          ? `${calculateGrowth(
              Number(profitRate.value),
              Number(lastProfitRate.value)
            ).toFixed(2)}% 同比增长`    
          : `${calculateGrowth(
              Number(lastProfitRate.value),
              Number(profitRate.value)
            ).toFixed(2)}% 同比减少 `;

      // 更新图表
      updateChart();

      loading.value = false;
    }
  } catch (error) {
    console.error("获取财务数据失败:", error);
    $ekMessage.error("获取数据失败，请重试");
  }
};
const calculateGrowth = (currentData, lastData) => {
  if (lastData === 0) {
    // 如果去年数据为0，避免除以0的错误，可以返回一个表示无限增长的数字，例如10000%
    return Infinity;
  } else {
    // 计算同比增长率
    console.log(currentData, lastData,'hhhhhhhh');
    
    const growth = ((currentData - lastData) / lastData) * 100;
    return growth;
  }
};
// 重置搜索
const resetSearch = () => {};

// 监听组件挂载
onMounted(async () => {
  await nextTick();
  initCharts();
  // 获取数据
  fetchData();
  // 添加窗口大小变化监听
  window.addEventListener("resize", handleResize);
});

// 清理
const cleanup = () => {
  window.removeEventListener("resize", handleResize);
  if (trendChart) trendChart.dispose();
  if (pieChart) pieChart.dispose();
  if (rateChart) rateChart.dispose();
};

// 组件卸载时清理
import { onBeforeUnmount } from "vue";
onBeforeUnmount(cleanup);
const handleChange = debounce(() => {
  fetchData();
}, 200); // 500毫秒后执行一次处理函数

watch(() => [props.dateRange, props.label], handleChange);
</script>

<style scoped lang="scss">
.finance-report {
  .search-section {
    padding: 10px 0;
  }

  .summary-card {
    // height: 120px;
    overflow: hidden;

    &.income {
      .card-content {
        // background: linear-gradient(135deg, #5470c6, #91cc75);
      }
    }

    &.cost {
      .card-content {
        // background: linear-gradient(135deg, #91cc75, #fac858);
      }
    }

    &.profit {
      .card-content {
        // background: linear-gradient(135deg, #fac858, #ee6666);
      }
    }

    &.rate {
      .card-content {
        //background: linear-gradient(135deg, #ee6666, #73c0de);
      }
    }

    .card-content {
      height: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: flex-start;
      //   color: #000;
      padding: 20px;

      .card-title {
        font-size: 14px;
        opacity: 0.9;
        margin-bottom: 8px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .card-change {
        font-size: 12px;

        &.up {
          color: #67c23a;
        }

        &.down {
          color: #f56c6c;
        }

        &.same {
          color: #909399;
        }
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .chart-container {
    width: 100%;
    height: 300px;
  }
}
</style>
